package logic

import (
	"context"
	"fmt"
	"gorm.io/gorm"
	"lucky/models"
	"net/http"

	"lucky/api/internal/svc"
	"lucky/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PayNotifyLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPayNotifyLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayNotifyLogic {
	return &PayNotifyLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PayNotifyLogic) PayNotify(r *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	err = r.ParseForm()
	if err != nil {
		return &types.Response{
			Message: "表单解析失败",
			Data:    nil,
			Code:    0,
		}, nil
	}
	fmt.Println(r.PostForm)

	tradeStatus := r.PostForm.Get("trade_status")
	outTradeNo := r.PostForm.Get("out_trade_no")

	if tradeStatus != "TRADE_SUCCESS" {
		return &types.Response{
			Message: "交易失败",
			Data:    nil,
			Code:    0,
		}, nil
	}

	if outTradeNo == "" {
		return nil, fmt.Errorf("订单不存在")
	}

	tx := models.DB.Debug().Begin()
	var order models.Order

	err = tx.Where("order_sn = ?", outTradeNo).First(&order).Error

	if err != nil {
		tx.Rollback()
		return &types.Response{
			Message: "没有此订单",
			Data:    nil,
			Code:    0,
		}, nil
	}

	if order.Status == 2 {
		tx.Rollback()
		return &types.Response{
			Message: "订单已支付",
			Data:    nil,
			Code:    0,
		}, nil
	}

	err = tx.Debug().Model(&models.Order{}).Where("order_sn = ?", outTradeNo).Update("status", 2).Error

	if err != nil {
		tx.Rollback()
		return &types.Response{
			Message: "订单状态修改失败",
			Data:    nil,
			Code:    0,
		}, nil

	}

	var orderItem []models.OrderItem
	err = tx.Debug().Where("order_sn = ?", order.ID).Find(&orderItem).Error

	if err != nil {
		tx.Rollback()
		return &types.Response{
			Message: "订单商品查询失败",
			Data:    nil,
			Code:    0,
		}, nil
	}

	for _, Item := range orderItem {
		result := tx.Debug().Model(&models.Product{}).Where("id = ? and stock = ?", Item.ProductId, Item.Quantity).
			UpdateColumn("stock", gorm.Expr("stock - ?", Item.Quantity))
		if result.Error != nil {
			tx.Rollback()
			return nil, fmt.Errorf("商品编号%d,库存扣减失败%v", Item.ProductId, result.Error)
		}

		if result.RowsAffected == 0 {
			tx.Rollback()
			return nil, fmt.Errorf("商品编号%d库存不足，扣减失败%v", Item.ProductId, result.Error)
		}
	}

	tx.Commit()

	return &types.Response{
		Message: "异步处理成功",
		Code:    200,
		Data:    nil,
	}, nil
}
